
//definition audio，include variable,prototype
var audio = function(){
    this.audioContext = null;
    this.mediaStreamSource = null;
    this.analyser = null;
    this.init();
};

audio.prototype = {
    init: function(){
        this.prepareAPI();
        this.getAudio();
    },
    prepareAPI: function(){
        //getUserMedia compatibility processing
        try {
            navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
        } catch(e) {
            throw new Error('Native device media streaming (getUserMedia) not supported in this browser.');
        }
        //audioContext compatibility processing
        try {
            this.audioContext = new (window.AudioContext || window.webkitAudioContext);
        } catch(e) {
            throw new Error('The Web Audio API is unavailable');
        }
    },
    getAudio: function(successFunc, errorFunc){
        var that = this;
        if(typeof successFunc != "function"){
            successFunc = function(stream){
                //make the stream(type MediaStream) become mediaStreamSource
                that.mediaStreamSource = that.audioContext.createMediaStreamSource(stream);
                //create analyser
                that.analyser = that.audioContext.createAnalyser();
                //set analyser's size
                that.analyser.fftSize = 256;
                //connect mediaStreamSource and analyser
                that.mediaStreamSource.connect(that.analyser);
            }
        }
        if(typeof errorFunc != "function"){
            errorFunc = function () {}
        }
        if (navigator.getUserMedia) {
            navigator.getUserMedia({
                'audio': true
            }, successFunc, errorFunc);    //successFunc is the callback function when it is success
        }
        else {
            alert('Native device media streaming (getUserMedia) not supported in this browser.');
        }
    },
    getByteDataArray: function(num){
        var array =  new Uint8Array(128);
        if(this.analyser && this.analyser.getByteFrequencyData){
            this.analyser.getByteFrequencyData(array);
            return array[num];
        }
        return -1;
    }
};
